﻿using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using T4UtilityBelt.Serializers;

namespace T4UtilityBelt.DataDesigns
{
    public class EntityModel
    {
        static EntityModel()
        {
            KeyType = "int";
            OptionalKeyType = "int?";
            SecondaryKeyType = "int";
            OptionalSecondaryKeyType = "int?";
        }

        public EntityModel()
        {
            _entities = new EntityCollection(this);
        }

        public static string KeyType { get; set; }
        public static string OptionalKeyType { get; set; }
        public static string SecondaryKeyType { get; set; }
        public static string OptionalSecondaryKeyType { get; set; }

        private readonly EntityCollection _entities;

        public EntityCollection Entities
        {
            get { return _entities; }
        }

        private readonly Dictionary<string, Entity> _entitiesByName = new Dictionary<string, Entity>();

        [XIgnore]
        public Dictionary<string, Entity> EntitiesByName
        {
            get { return _entitiesByName; }
            //set { _entitiesByName = value; }
        }

        //public string Namespace { get; set; }

        public void FixModel()
        {
            foreach (Entity e in Entities)
            {
                if (_entitiesByName.ContainsKey(e.Name))
                {
                    throw new DuplicateKeyException("Entity is defined twice: " + e.Name);
                }
                _entitiesByName.Add(e.Name, e);

            }

            foreach (Entity e in Entities)
            {
                e.FixModel(this);
            }
        }

        public Entity GetEntity(string name)
        {
            if (EntitiesByName.ContainsKey(name))
            {
                return EntitiesByName[name];
            }
            return null;
        }
    }
}